package com.heima.media.listener;

import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsService;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Component
public class PublishArticleListener {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private IWmNewsService wmNewsService;
    @Autowired
    private IAuditService auditService;

    @PostConstruct
    public void receiveMsg() {
        RBlockingDeque<Integer> blockingDeque = redissonClient.getBlockingDeque("publish-article-queue");

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        //从队列中弹出消息
                        Integer newsId = blockingDeque.poll(30, TimeUnit.SECONDS);
                        if (newsId != null) {
                            WmNews wmNews = wmNewsService.getById(newsId);
                            //发布app文章
                            Long articleId = auditService.createApArticle(wmNews); //需要把createApArticle改成public并且定义到interface接口上
                            wmNews.setArticleId(articleId);
                            wmNews.setStatus(9);
                            wmNewsService.updateById(wmNews);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
